package com.aust.syn;

/**
 * 线程不安全：银行取钱
 */
public class UnsafeBank {
    public static void main(String[] args) {
        // 账户
        Account account = new Account(100, "结婚基金");

        Drawing boy = new Drawing(account, 50, 100);
        Drawing girl = new Drawing(account, 100, 0);
        boy.setName("boy");
        girl.setName("girl");

        boy.start();
        girl.start();
    }
}

/**
 * 账户
 */
class Account {
    int money; // 余额
    String name; // 卡号

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

/**
 * 模拟取钱
 */
class Drawing extends Thread {
    /**
     * 账户
     */
    Account account;

    /**
     * 取钱金额
     */
    int drawingMoney;

    /**
     * 手中余额
     */
    int nowMoney;

    public Drawing(Account account, int drawingMoney, int nowMoney) {
        this.account = account;
        this.drawingMoney = drawingMoney;
        this.nowMoney = nowMoney;
    }

    /**
     * 取钱操作
     */
    @Override
    public void run() {
        /**
         * 锁的对象就是变化的量即增删改的对象
         */
        synchronized (account) {
            // 判断是否有钱
            if (account.money - drawingMoney < 0) {
                System.out.println(Thread.currentThread().getName() + "余额不足无法取出");
                return;
            }

            try {
                /**
                 * sleep能够放大问题的发生性
                 */
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            // 卡内余额 = 余额 - 取出的钱
            account.money -= drawingMoney;
            // 手中余额 = 取出的钱 + 手中金额
            nowMoney += drawingMoney;

            System.out.println(account.name + "余额为：" + account.money);
            System.out.println(Thread.currentThread().getName() + "手中的钱为：" + nowMoney);
        }
    }
}
